package ltd.jdsoft.cute.perm.manager;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import ltd.jdsoft.cute.perm.model.Menu;
import ltd.jdsoft.cute.perm.model.Role;
import ltd.jdsoft.cute.perm.model.User;
import ltd.jdsoft.cute.perm.service.MenuService;
import ltd.jdsoft.cute.perm.service.RoleService;

@Component
public class MenuManager {

  @Autowired
  private MenuService menuService;
  @Autowired
  private RoleService roleService;

  /**
   * 获取用户对应的菜单，拼接成前端需要的格式。按照目前前端的设计，只需要一个parent对应多个child即可。
   * 
   * @param user
   * @return
   */
  public List<JSONObject> getMenuList(User user) {
    List<JSONObject> menuList = new ArrayList<JSONObject>();
    Role role = roleService.get(user.getRoleId());
    List<Menu> userMenuList = menuService.getMenuList(role.getMenuIds());
    for (Menu parentMenu : userMenuList) {
      // parent=0的代表父级菜单
      if (parentMenu.getParentId() > 0) {
        continue;
      }
      JSONObject parentMenuJson = new JSONObject();
      parentMenuJson.put("name", parentMenu.getName());
      parentMenuJson.put("iconCls", parentMenu.getIconCls());

      List<Menu> childs = new ArrayList<Menu>();
      for (Menu childMenu : userMenuList) {
        if (childMenu.getParentId() == parentMenu.getId()) {
          childs.add(childMenu);
        }
      }

      parentMenuJson.put("childs", childs);

      menuList.add(parentMenuJson);
    }

    return menuList;
  }
}
